import cv2
import numpy as np


def save_2d_image(image, text_path):
    h, w = image.shape[:2]
    area = w * h
    with open(text_path, 'w') as f:
        for idx in range(area):
            y = int(idx / w)
            x = idx - y * w
            f.write('{}\n'.format(image[y, x]))


def generate():
    image_path = './person.jpg'
    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    image = cv2.resize(image, (100, 100))
    print(image.shape)
    save_2d_image(image, './sample_input.txt')

    # generate filter
    filter_size = 5
    f = cv2.getGaussianKernel(filter_size, 1)
    f = np.outer(f, f)
    save_2d_image(f, './sample_filter.txt')

    # generate sample result
    dst = cv2.filter2D(image, -1, f)
    save_2d_image(dst, './sample_output.txt')

    cv2.imshow("image", image)
    cv2.imshow("result", dst)
    cv2.waitKey(0)


def view_output(text_path):
    data = []
    with open(text_path, 'r') as f:
        for line in f.readlines():
            v = float(line.strip())
            v = int(v)
            if v > 255: v = 255
            elif v < 0: v = 0
            data.append(v)
    data = np.array(data)
    data = data.reshape((100, 100))
    data = data.astype(np.uint8)
    cv2.imshow('data', data)
    cv2.waitKey(0)


if __name__ == '__main__':
    # generate()
    view_output('output.txt')
